﻿using Stackoverflow.Web.Controllers;
using Stackoverflow.Core.Questions;
using Stackoverflow.EntityFramework.Repositories;
using Stackoverflow.Web.Models;
using System;
using System.Collections.Generic;
using System.Linq;
using System.Net;
using System.Net.Http;
using System.Web.Http;
using System.Threading.Tasks;
using Microsoft.AspNet.Identity;
using Microsoft.AspNet.Identity.EntityFramework;

namespace Stackoverflow.Web.Controllers
{
    public class QuestionController : BaseApiController<Question,QuestionModel,QuestionModel>
    {
        private UserManager<IdentityUser> m_UserManager { get; set; }
        public QuestionController(IQuestionRepository repository,
            UserManager<IdentityUser> userManager): base(repository)
        {
            m_UserManager = userManager;
        }

        public override IHttpActionResult GetBy(Guid id)
        {
            return base.GetBy(id);
        }

        [Route("api/question/getquestions")]
        public IHttpActionResult GetQuestions()
        {
            List<QuestionModel> results = new List<QuestionModel>();
            try
            {
                var questions = Repository.GetAll();
               
                results = questions.Select(item => new QuestionModel()
                {
                    Id = item.Id,
                    Title = item.Title,
                    Views = item.Views,
                    Vote = item.Vote,
                    UserId = item.UserId,
                    Username = string.IsNullOrEmpty(item.UserId) ? "" : m_UserManager.FindById(item.UserId).UserName
                }).ToList();

                return Ok(results);
            }
            catch (Exception ex)
            {
                return InternalServerError(ex);
            }
        }
    }
}
